package com.cy.store.service.impl;

import com.cy.store.entity.User;
import com.cy.store.mapper.UserMapper;
import com.cy.store.service.IUserService;
import com.cy.store.service.ex.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.UUID;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;


    /**
     * 注册
     * @param user 用户数据
     */
    @Override
    public void reg(User user) {





        String usename = user.getUsername();

        // 判断用户是否存在
        User result = userMapper.findByUsername("usename");
        if(result != null){
            throw new UsernameDuplicatedException("用户已存在");
        }


        // 加密
        String oldPassword = user.getPassword();
        String salt = UUID.randomUUID().toString().toUpperCase();
        String md5Password = getMD5Password(oldPassword,salt);
        user.setPassword(md5Password);
        user.setSalt(salt);





        // 补充数据
        user.setIsDelete(0);
        user.setCreatedUser(user.getUsername());
        user.setModifiedUser(user.getUsername());

        Date date = new Date();
        user.setCreatedTime(date);
        user.setModifiedTime(date);





        // 插入数据
        Integer rows = userMapper.insert(user);
        if(rows != 1){
            throw new InsertException("在用户注册时，出现未知异常");
        }
    }

    /**
     * 登录
     * @return  一部分用户数据
     * 功能：存放数据
     *
     * 1：登录成功  2：密码错误  3：
     */
    @Override
    public User login(String username, String password) {

        User result = userMapper.findByUsername(username);      // 获取这个用户
        if(result == null){
            throw new UserNotFoundException("用户不存在");
        }

        String olePassword = result.getPassword();  // 获取这个用户的密码

        String salt = result.getSalt();     // 获取这个用户的盐值
        String newMd5Password = getMD5Password(password, salt);     // 获取输入的密码，并加密

        // 比较数据功能
        if(!olePassword.equals(newMd5Password)){
            throw new PasswordNotMatchException("密码错误");
        }

        if(result.getIsDelete() == 1){
            throw new UserNotFoundException("用户不存在");
        }



        User user = new User();
        user.setUid(result.getUid());
        user.setUsername(result.getUsername());
        user.setAvatar(result.getAvatar());


        return user;
    }

    /**
     * 修改密码
     * @param oldPassword 用户的原密码
     * @param newPassword 新密码
     */
    public void changePassword(Integer uid, String username, String oldPassword, String newPassword) {

        User result = userMapper.findByUid(uid);

        // 查看这个用户是否存在
        if(result == null || result.getIsDelete() == 1){
            throw new UserNotFoundException("用户不存在");
        }

        // 比对密码是否正确
        String oldMd5Password = getMD5Password(oldPassword, result.getSalt());
        if( !result.getPassword().equals(oldMd5Password) ){
            throw new PasswordNotMatchException("密码错误");
        }

        // 更新数据
        String newMd5Password = getMD5Password(newPassword, result.getSalt());
        Integer rows = userMapper.updatePasswordByUid(uid, newMd5Password, username, new Date());
        if(rows != 1){
            throw new UpdateException("更新出现未知异常");      // 可以测试
        }

    }


    /**
     * 根据用户的id查用户的数据
     * @return 用户名、电话、邮箱、性别
     */
    public User getByUid(Integer uid) {


        User result = userMapper.findByUid(uid);

        // 判断用户是否存在
        if (result==null || result.getIsDelete()==1){
            throw new UserNotFoundException("用户不存在");
        }

        // 过滤无用信息
        User user = new User();
        user.setUsername(result.getUsername());
        user.setPhone(result.getPhone());
        user.setEmail(result.getEmail());
        user.setGender(result.getGender());




        return user;
    }

    /**
     * 更新用户信息
     * @param uid  username 改谁的
     * @param user 修改后的信息
     */
    public void changeInfo(Integer uid, String username, User user) {

        User result = userMapper.findByUid(uid);

        // 判断用户是否存在
        if (result==null || result.getIsDelete()==1){
            throw new UserNotFoundException("用户不存在");
        }

        // 补充必要数据
        user.setUid(uid);
        user.setModifiedUser(username);
        user.setModifiedTime(new Date());

        // 更新用户信息
        Integer rows = userMapper.updateInfoByUid(user);
        if(rows != 1){
            throw new UpdateException("更新时出现未知异常");
        }

    }

    /**
     * 更新头像
     */
    @Override
    public void changeAvatar(Integer uid, String avatar, String username) {

        User result = userMapper.findByUid(uid);
        if(result == null || result.getIsDelete().equals(1)){
            throw new UserNotFoundException("用户不存在");
        }

        Integer rows = userMapper.updateAvatarByUid(uid, avatar, username, new Date());

        if(rows != 1){
            throw new UpdateException("更新时出现未知异常");
        }
    }


    // md5加密功能
    private String getMD5Password(String password, String salt){

        for(int i = 0; i<3; i++){
            password = DigestUtils.md5DigestAsHex((salt+password+salt).getBytes()).toUpperCase();
        }

        return password;
    }

}
